#ifndef ADMINDEVICEMANAGE_H
#define ADMINDEVICEMANAGE_H

#include <QWidget>
#include <QTableView>
#include <QHeaderView>
#include <QDateTime>
#include <QMouseEvent>
#include "sqlitemanage.h"
#include "settingmanage.h"
#include "adddevicegroup.h"
#include "modigroupdialog.h"
#include "groupdeletedialog.h"
#include "logclass.h"

namespace Ui {
class AdminDeviceManage;
}

class DeviceModel : public QSqlRelationalTableModel {
public:
    explicit DeviceModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
        : QSqlRelationalTableModel(parent, db) {
        setTable("users");
        setEditStrategy(QSqlTableModel::OnManualSubmit); // 手动提交修改
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override {
        // 只在编辑角色时处理
        if (role != Qt::EditRole)
            return QSqlTableModel::setData(index, value, role);
        QString columnName = this->record().fieldName(index.column());  // 获取列名
        if ((columnName == "name" || columnName == "type" || columnName == "location") &&
            value.toString().trimmed().isEmpty())// 检查必填字段是否为空
        {
            QMessageBox::warning(nullptr, tr("警告"), tr("%1 不能为空!").arg(columnName));
            return false; // 拒绝空值
        }
        if (columnName == "installation_date") {// 日期字段验证
            QDate date = QDate::fromString(value.toString(), "yyyy-MM-dd");
            if (!date.isValid()) {
                QMessageBox::warning(nullptr, tr("警告"),tr("请输入有效的日期格式 (年-月-d日)!"));
                return false;
            }
        }
        return QSqlTableModel::setData(index, value, role);// 调用基类实现进行实际的数据设置
    }
};

class AdminDeviceManage : public QWidget
{
    Q_OBJECT

public:
    explicit AdminDeviceManage(QWidget *parent = nullptr);
    ~AdminDeviceManage();
    void loadComboxData();
    bool addDialog();
    bool modiDialog();
    bool deleteDialog();
    void setUserName(QString &name);
public slots:
    void applyFilter();
    void clearFilter();

protected:
    bool eventFilter(QObject *watched, QEvent *event) override;

private:
    Ui::AdminDeviceManage *ui;
    SqliteManage *m_pSqliteManage;
    SettingManage *m_pSettingManage;
    AddDeviceGroup *m_pAddDeviceGroup;
    ModiGroupDialog *m_pModiGroup;
    GroupDeleteDialog *m_pDeleteGroup;
    DeviceModel *model;
    LogClass *m_pLog;
    QString Group1;
    QString Group2;
    QString NewGroup2;
    QString username;
    void setupUI();
    void loadData();
    void addDevice();
    void deleteDevice();
    void saveChanges();
};

#endif // ADMINDEVICEMANAGE_H
